package com.onpositive.html.utils;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.onpositive.html.model.HyperLink;
import com.onpositive.html.model.HyperLinkEntry;
import com.onpositive.html.model.StringEntry;
import com.onpositive.html.model.Table;

public class TableGrabber {
	
	public static List<Table> grabTables(Element element){
		
		Elements tableElements = element.select("table");
		ArrayList<Table> list = new ArrayList<Table>(); 
		for(Element te : tableElements){
			Table table = grabTable(te);
			if(table==null)
				continue;
			
			list.add(table);
		}
		return list;
	}

	private static Table grabTable(Element te)
	{
		Table table = new Table();
		
		Elements captionElements = te.select("caption");
		if(captionElements!=null&&!captionElements.isEmpty()){
			Element caption = captionElements.first();
			table.setCaption(caption.text());
		}
		
		Element parent = te.parent();
		int si = te.siblingIndex();
		Elements headers = parent.select("h3");
		for( int i = headers.size() ; i >0 ; i--){
			Element hd = headers.get(i-1);
			if(hd.siblingIndex()>si)
				continue;
			
			String text = hd.text();
			table.setTitle(text);
			break;
		}		
		
		Elements theadElements = te.select("thead");
		for(Element thead : theadElements){
			Elements trElements = thead.select("tr");
			for(Element tr : trElements){
				Elements thElements = tr.select("th");
				ArrayList<String> header = new ArrayList<String>();
				for(Element th : thElements){
					header.add(th.text());
				}
				table.addHeadersArray(header);
			}
		}
		int columnsCount=0;
		for(ArrayList<String> lst : table.getHeaders()){
			columnsCount = Math.max(columnsCount, lst.size());
		}		
		table.setColumnsCount(columnsCount);
		Elements bodyElements = te.select("tbody");
		for(Element tbody : bodyElements){
			Elements trElements = tbody.select("tr");
			for(Element tr : trElements){
				Elements tdElements = tr.select("td");
				int rowLength = tdElements.size();
				for(int i = 0 ; i < rowLength ; i++ ){
					Element td = tdElements.get(i);
					Elements children = td.children();
					Elements refs = children.select("a");
					if(refs.isEmpty()){
						String text = td.text();
						table.getColumns().get(i).add(new StringEntry(text));
					}
					else{
						Element refElement = refs.first();
						String link = refElement.attr("href");						
						String caption = refElement.text();
						HyperLink hl = new HyperLink(link, caption);
						table.getColumns().get(i).add(new HyperLinkEntry(hl));
					}
				}				
			}
		}		
		return table;
	}
}
